package cn.yuanqiao.archive.qzj.service.impl;

import cn.yuanqiao.archive.qzj.domain.YqdaQzjTree;
import cn.yuanqiao.archive.qzj.mapper.YqdaQzjTreeMapper;
import cn.yuanqiao.archive.qzj.service.YqdaQzjTreeService;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class YqdaQzjTreeServiceImpl implements YqdaQzjTreeService {
    @Autowired
    private YqdaQzjTreeMapper yqdaQzjTreeMapper;

    @Override
    public int insertYqdaQzjTree(YqdaQzjTree yqdaQzjTree) {
        yqdaQzjTree.setId(SnowflakeIdGenerator.generateId());
        yqdaQzjTree.setTenantCode(SecurityUtils.getTenantCode());
        return yqdaQzjTreeMapper.insertYqdaQzjTree(yqdaQzjTree);
    }

    @Override
    public int updateYqdaQzjTree(YqdaQzjTree yqdaQzjTree) {
        return yqdaQzjTreeMapper.updateYqdaQzjTree(yqdaQzjTree);
    }

    @Override
    public List<TreeSelect> QzjTree() {
        List<YqdaQzjTree> qzjTreeList = yqdaQzjTreeMapper.getTreeList(SecurityUtils.getTenantCode());
        List<TreeSelect> treeSelects = new ArrayList<>();
        for(YqdaQzjTree qzjTree:qzjTreeList){
            //循环第一级
            if(qzjTree.getParentId()!=null && qzjTree.getParentId() == 0){
                TreeSelect rootTree = new TreeSelect();
                rootTree.setId(qzjTree.getId());
                rootTree.setLabel(qzjTree.getName());
                rootTree.setChildren(child(qzjTree.getId(),qzjTreeList));
                treeSelects.add(rootTree);
            }
        }
        return treeSelects;
    }

    private List<TreeSelect> child(Long id, List<YqdaQzjTree> qzjTreeList) {
        List<TreeSelect> children = new ArrayList<>();
        for(YqdaQzjTree qzjTree:qzjTreeList){
            if(qzjTree!=null && qzjTree.getParentId()!=null && qzjTree.getParentId().longValue() == id.longValue()){
                TreeSelect rootTree = new TreeSelect();
                rootTree.setId(qzjTree.getId());
                rootTree.setLabel(qzjTree.getName());
                rootTree.setTenantCode(qzjTree.getTenantCode());
                rootTree.setChildren(child(qzjTree.getId(),qzjTreeList));
                children.add(rootTree);
            }
        }
        return children;
    }

    @Override
    public int delYqdaQzjTree(Long [] id) {
        return yqdaQzjTreeMapper.delYqdaQzjTree(id);
    }

    @Override
    public YqdaQzjTree selectYqdaQzjTreeById(Long id) {
        return yqdaQzjTreeMapper.selectYqdaQzjTreeById(id);
    }
}
